package com.example.utils;

import javax.servlet.http.Part;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * 文件上传接口
 */
public class LocalFileUpload {

    public static String getBase64Image(Part filePart) throws IOException {
//        String fileName = filePart.getSubmittedFileName();
        // 将文件内容转换为ByteArray
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (InputStream fis = filePart.getInputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
        }

        byte[] fileBytes = baos.toByteArray();

        // 将文件字节数组编码为Base64字符串
        return "data:image/jpg;base64," + Base64.getEncoder().encodeToString(fileBytes);
    }
}
